<template>
  <view class="main-bg">
    <z-nav-bar backState='3000' @backClick='backClick' type='transparent' :titleCenter='true' title='' />
    <public-module />
    <view class="header-gradient">
      <text class="main-title">委托人身份证上传</text>
    </view>
    <view class="content-area">
      <view class="section-title">委托代理人身份证上传:</view>
      <view class="desc">无委托人无需上传</view>
      <view class="desc">所拍证件需四角齐全，字迹清晰，无反光；</view>
      <view class="upload-list">
        <view class="upload-card" @click="openFileSelector('front')">
          <input type="file" style="display:none;" ref="sfzzmInput" accept="image/*" @change="handleFileChange('front', $event)" />
          <image v-if="idcardFrontUrl" :src="idcardFrontUrl" class="id-img" mode="aspectFill"/>
          <view v-else class="upload-placeholder">
            <view>正面</view>
            <view class="tip">点击上传身份证正面</view>
          </view>
        </view>
        <view class="upload-card" @click="openFileSelector('back')">
          <input type="file" style="display:none;" ref="sfzfmInput" accept="image/*" @change="handleFileChange('back', $event)" />
          <image v-if="idcardBackUrl" :src="idcardBackUrl" class="id-img" mode="aspectFill"/>
          <view v-else class="upload-placeholder">
            <view>反面</view>
            <view class="tip">点击上传身份证反面</view>
          </view>
        </view>
      </view>
      <view style="margin-top: 40rpx;margin-left: 25rpx;">
        <button type="primary" style="width: 80vw; max-width: 320px; display: block; margin: 0 auto;" @click="saveIdcard">保存</button>
      </view>
    </view>
  </view>
</template>

<script>
function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

export default {
  data() {
    return {
      id: uuidv4(),
      idcardFrontUrl: '',
      idcardBackUrl: '',
      sfzzmFile: null,
      sfzfmFile: null
    }
  },
  onLoad() {
    // 自动回显缓存
    const id = uni.getStorageSync('idcard_agent_id');
    if (id) this.id = id;
    const frontBase64 = uni.getStorageSync('idcard_agent_front_base64');
    const backBase64 = uni.getStorageSync('idcard_agent_back_base64');
    const frontUrl = uni.getStorageSync('idcard_agent_front_url');
    const backUrl = uni.getStorageSync('idcard_agent_back_url');
    // 优先用base64回显图片
    if (frontBase64) {
      this.idcardFrontUrl = frontBase64;
      this.sfzzmFile = this.base64ToFile(frontBase64, 'sfzzm.jpg');
    } else if (frontUrl) {
      this.idcardFrontUrl = frontUrl;
    }
    if (backBase64) {
      this.idcardBackUrl = backBase64;
      this.sfzfmFile = this.base64ToFile(backBase64, 'sfzfm.jpg');
    } else if (backUrl) {
      this.idcardBackUrl = backUrl;
    }
  },
  methods: {
    backClick() {
      uni.navigateBack();
    },
    openFileSelector(type) {
      // 先移除旧的 input，避免多次插入
      let oldInput = document.getElementById('dynamic-input-' + type);
      if (oldInput) oldInput.remove();

      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.id = 'dynamic-input-' + type;
      input.style.display = 'none';

      input.onchange = (e) => {
        const file = input.files[0];
        if (!file) return;

        // 校验类型
        const whitelist = ['jpg', 'jpeg', 'png'];
        const suffix = file.name.split('.').pop().toLowerCase();
        if (!whitelist.includes(suffix)) {
          uni.showToast({ title: '文件格式错误', icon: 'none' });
          return;
        }
        // 校验大小
        if (file.size > 50 * 1024 * 1024) {
          uni.showToast({ title: '单个文件请勿超过50M', icon: 'none' });
          return;
        }

        // 预览
        const url = URL.createObjectURL(file);
        if (type === 'front') {
          this.sfzzmFile = file;
          this.idcardFrontUrl = url;
        } else {
          this.sfzfmFile = file;
          this.idcardBackUrl = url;
        }
      };

      document.body.appendChild(input);
      input.click();
    },
    handleFileChange(type, e) {
      const file = e.target.files[0];
      if (!file) return;
      const url = URL.createObjectURL(file);
      if (type === 'front') {
        this.sfzzmFile = file;
        this.idcardFrontUrl = url;
      } else {
        this.sfzfmFile = file;
        this.idcardBackUrl = url;
      }
    },
    base64ToFile(base64, filename) {
      // H5专用
      const arr = base64.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    saveIdcard() {
      if (!this.sfzzmFile || !this.sfzfmFile) {
        uni.showToast({ title: '请上传身份证正反面', icon: 'none' });
        return;
      }
      uni.showLoading({ title: '保存中...' });
      // 每次保存都生成新uuid
      this.id = uuidv4();
      uni.setStorage({ key: 'idcard_agent_id', data: this.id });
      this.fileToBase64(this.sfzzmFile, (base64) => {
        uni.setStorage({ key: 'idcard_agent_front_base64', data: base64 });
      });
      this.fileToBase64(this.sfzfmFile, (base64) => {
        uni.setStorage({ key: 'idcard_agent_back_base64', data: base64 });
      });
      const formData = new FormData();
      formData.append('id', this.id);
      formData.append('sfzzm', this.sfzzmFile);
      formData.append('sfzfm', this.sfzfmFile);
      fetch('http://124.222.44.60:9997/jeecg-boot/blrsfz/add', {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(data => {
          uni.hideLoading();
          if (data && data.code === 200) {
            uni.setStorage({ key: 'idcard_agent_front_url', data: this.idcardFrontUrl });
            uni.setStorage({ key: 'idcard_agent_back_url', data: this.idcardBackUrl });
            uni.showToast({ title: '保存成功', icon: 'success' });
          } else {
            uni.showToast({ title: data.message, icon: 'none' });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({ title: err, icon: 'none' });
        });
    },
    fileToBase64(file, cb) {
      const reader = new FileReader();
      reader.onload = function (e) {
        cb(e.target.result);
      };
      reader.readAsDataURL(file);
    }
  }
}
</script>

<style scoped>
.main-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #6db3f2 0%, #1e69de 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.header-gradient {
  width: 100vw;
  height: 110rpx;
  background: linear-gradient(135deg, #8ec5fc 0%, #e0c3fc 100%);
  border-bottom-left-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding-bottom: 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(30,105,222,0.08);
}
.main-title {
  font-size: 40rpx;
  color: #222;
  font-weight: bold;
  letter-spacing: 2rpx;
}
.content-area {
  width: 86vw;
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.section-title {
  font-size: 38rpx;
  font-weight: bold;
  margin-bottom: 12rpx;
  color: #222;
  text-align: left;
}
.desc {
  color: #222;
  font-size: 32rpx;
  margin-bottom: 32rpx;
  text-align: left;
}
.upload-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 40rpx;
  align-items: center;
  justify-content: flex-start;
}
.upload-card {
  width: 90vw;
  max-width: 600rpx;
  height: 240rpx;
  border: 2rpx dashed #111;
  border-radius: 18rpx;
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: box-shadow 0.2s;
  box-shadow: 0 4rpx 16rpx rgba(30,105,222,0.10);
  overflow: hidden;
  position: relative;
  border-style: dashed;
  /* border-image: repeating-linear-gradient(90deg, #111 0 10px, transparent 10px 16px) 30; */
}
.upload-card:active {
  box-shadow: 0 2rpx 8rpx rgba(30,105,222,0.18);
}
.upload-placeholder {
  color: #111;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
.upload-placeholder .tip {
  color: #111;
}
.id-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 18rpx;
}
</style> 